<?php

/**
 * 商品管理
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/23
 * Time: 9:52
 */
class Api_Products extends PhalApi_Api
{
    public function getRules()
    {
        return [
            'details' => [
                'id' => ['name' => 'id', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '商品id'],
            ],
            'getSidNature' => [
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
            ],
            'getSelect' => [
                'id' => ['name' => 'id', 'type' => 'int', 'require' => false, 'desc' => '门店id /没有则传空'],
            ],
            'screening' => [
                'category' => ['name' => 'category', 'type' => 'string', 'require' => false, 'desc' => '分类名'],
                'brand' => ['name' => 'brand', 'type' => 'string', 'require' => false, 'desc' => '品牌名'],
                'retail_price' => ['name' => 'retail_price', 'type' => 'string', 'require' => false, 'desc' => '需要传一个默认值DESC,商品价格区间,从大到小传DESC,从小到大传ASC'],
                'page' => ['name' => 'page', 'type' => 'int', 'require' => false, 'desc' => '页数'],
            ],
            'review' => [
                'gid' => ['name' => 'gid', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '商品id'],
                'uid' => ['name' => 'uid', 'type' => 'string', 'require' => true, 'desc' => '用户名'],
                'message' => ['name' => 'message', 'type' => 'string', 'require' => true, 'desc' => '留言内容'],
                'score' => ['name' => 'score', 'type' => 'string', 'require' => true, 'desc' => '评分'],
            ],
            'reviewList' => [
                'gid' => ['name' => 'gid', 'type' => 'int', 'min' => 1, 'require' => true, 'desc' => '商品id'],
            ],
            'shelves' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => true, 'desc' => '用户id'],
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
                'parameter' => ['name' => 'parameter', 'type' => 'string', 'require' => true, -1404, 'desc' => '上架属性'],
                'number' => ['name' => 'number', 'type' => 'string', 'require' => false, -1407, 'desc' => '数量'],
                'shop_price' => ['name' => 'shop_price', 'type' => 'int', 'require' => true, 'desc' => '商家自定义价格'],

            ],
            'shelvesData' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => true, 'desc' => '用户id'],
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
            ],
            'downShelves' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => true, 'desc' => '用户id'],
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
                'did' => ['name' => 'did', 'type' => 'string', 'require' => false, 'desc' => '商品id'],
                'parameter' => ['name' => 'parameter', 'type' => 'string', 'require' => true, 'desc' => '下架属性/商品属性值id["id","id""id"]'],
                'number' => ['name' => 'number', 'type' => 'string', 'require' => false, 'desc' => '数量'],
            ],
            'downShelvesData' => [
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => true, 'desc' => '用户id'],
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
            ],
            'number' => [
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
                'parameter' => ['name' => 'parameter', 'type' => 'array', 'require' => true, 'format' => 'json', 'desc' => '库存参数/参数格式["id","id","id"]'],
                'uid' => ['name' => 'uid', 'type' => 'int', 'require' => false, 'desc' => '用户id/2.0丢弃'],
            ],
            'totalNumber'=>[
                'sid' => ['name' => 'sid', 'type' => 'int', 'require' => true, 'desc' => '门店id'],
                'gid' => ['name' => 'gid', 'type' => 'int', 'require' => true, 'desc' => '商品id'],
            ]
        ];
    }

    /**
     * 获取商品详细数据
     * @desc 根据id返回详细数据
     * @return int id 商品id
     * @return string title 标题
     * @return string brand 品牌
     * @return string retail_price 商品零售价
     * @return string earnest 商品类型
     * @return string weight 商品重量
     * @return int num 数量
     * @return string images_url 详情轮播图片
     * @return array images 显示图片
     * @return string isrecommend 是否推荐
     * @return int isrecommend 是否推荐
     * @return string barcode 条形码
     */
    public function details()
    {
        $products = new Domain_HomePageProducts();
        $category = new Model_Category;
        $field = 'id,title,type,brand,retail_price,earnest,weight,num,image_url,images,isrecommend,barcode';

        $details = $products->getByIdDetails($this->id, $field);

        $arg = [
            'id' => $details['type']

        ];
        $type = $category->getDataByField('category', $arg);

        $details['type'] = $type['category'];
        $details['images'] = json_decode($details['images'], true);

        return $details;
    }

    /**
     * 获取商品的属性值
     * @desc 根据商品所在的门店id,获取对应的属性值
     * @return string nature 属性名
     * @return array details 商品属性详细信息
     * @return string details.valueID 属性名id
     * @return string details.value 属性值
     */
    public function getSidNature()
    {
        $product = new Domain_HomePageProducts();
        $arg = [
            'sid' => $this->sid,
            'gid' => $this->gid
        ];

        $shelvesData = $product->getByIdSidNatureVal('nature_val', $arg); //上架的数据

        foreach ($shelvesData as $k) {

            $sku = $product->getSku($k['nature_val']); //查询sku值

            $nat_val = json_decode($sku['values']);

            foreach ($nat_val as $v) {

                $values = $product->getByIdUidNatureVal(['id' => $v]);

                $nature[] = $values[0]['n_id'];

                $nature_val[] = $values[0];

            }

        }

        $nature = array_unique($nature);
        $nature_val = DI()->helper->array_unique_fb($nature_val);

        //拼接属性值和名
        foreach ($nature as $k2) {
            $natu_val = array();
            $nature_name = $product->getByNIdNature($k2);
            foreach ($nature_val as $ke) {
                if ($ke[1] == $k2) {
                    $natu_val[] = array(
                        'valueID' => $ke[0],
                        'value' => $ke[2],
                    );
                }
            }

            $date[] = array(
                'nature' => $nature_name[0]['nature'],
                'details' => $natu_val,
            );
        }
        return $date;
    }

    /**
     * 获取筛选分类列表
     * @desc 获取俱乐部详情和商品筛选列表的分类
     * @return array    categorys   分类名
     * @return string   brands  品牌名
     * @return string   ranges  价格区间
     */
    public function getSelect()
    {
        $category = new Domain_Category();
        $brand = new Domain_Brand();
        $range = new Domain_Range();
        $shop = new Domain_HomePageShop();
        $product = new Domain_HomePageProducts();

        if ($this->id) {
            $gid = $shop->getBySidGid($this->id);
            $newGid = json_decode($gid['gid'], true);
            $explodeData = explode(',', $newGid);
            $result = $product->getByGid($explodeData, 'brand,category', count($explodeData)); //查询类型数据
            $brandData = array_values(array_unique(array_column($result, 'brand')));//取出品牌
            $brandData[] = '所有品牌';
            $d = array_column($result, 'category');

            foreach ($d as $k2 => $v2) {
                $arg = [
                    'id' => $v2
                ];
                $type[] = $category->getDataByField('category', $arg); //循环查询所有类型
            }
            $categoryData = array_values(array_unique(array_column($type, 'category')));
            $categoryData[] = '所有类别';
            return [
                'categorys' => $categoryData,
                'brands' => $brandData,
                'ranges' => array_column($range->getList(), 'price_range'),
            ];


        } else {
            $e = array_column($category->getList(), 'category');
            $e[] = '所有类别';

            $f = array_column($brand->getList(), 'brand');
            $f[] = '所有品牌';
            return [
                'categorys' => $e,
                'brands' => $f,
                'ranges' => array_column($range->getList(), 'price_range'),
            ];
        }


    }

    /**
     * 获取筛选列表
     * @desc 根据商品类别,品牌,价格 获取筛选列表.默认空返回所有
     * @return string id 商品id
     * @return string title 标题
     * @return string brand 品牌
     * @return string type 类型
     * @return string earnest 定金
     * @return string retail_price 零售价
     * @return string image_url 图片地址
     * @return boolean false 搜索不到数据
     */
    public function screening()
    {
        $products = new Domain_HomePageProducts();
        $category = new Domain_Category();
//        $conversion = DI()->helper->conversion($this->retail_price);
//        $field = 'id,title,brand,type,earnest,retail_price,image_url';

        $page = $this->page * 10 ? $this->page * 10 : 1;

        if (empty($this->category)) {
            unset($this->category);
        }
        if (empty($this->brand)) {
            unset($this->brand);
        }
        if (empty($this->retail_price)) {
            unset($this->retail_price);
        }

        if (!empty($this->category)) {
            $arg = [
                'category' => $this->category
            ];
            $newCategory = $category->getDataByField('id', $arg);
        }

        if (!empty($this->category)) {
            if (!empty($this->brand)) {
                if (!empty($this->retail_price)) {
                    $data = [
                        'category' => $newCategory['id'],
                        'brand' => $this->brand,
                        'retail_price' => $this->retail_price,
                    ];


                } else {
                    //retail_price 为空的时候
                    $data = [
                        'category' => $newCategory['id'],
                        'brand' => $this->brand,
                    ];
                }
            } else {
                //brand 为空的时候
                if (!empty($this->retail_price)) {
                    $data = [
                        'category' => $newCategory['id'],
                        'retail_price' => $this->retail_price,
                    ];


                } else {
                    //brand retail_price 为空的时候
                    $data = [
                        'category' => $newCategory['id']
                    ];
                }
            }
        } else {
            //category为空的时候
            if (!empty($this->brand)) {
                if (!empty($this->retail_price)) {
                    $data = [
                        'brand' => $this->brand,
                        'retail_price' => $this->retail_price,
                    ];


                } else {
                    $data = [
                        'brand' => $this->brand
                    ];
                }
            } else {
                //category  brand 为空的时候
                if (!empty($this->retail_price)) {
                    $data = [
                        'retail_price' => $this->retail_price,
                    ];


                } else {
                    //category  brand retail_price 为空的时候
                    $a = $products->getDefaultList($page);
                    foreach ($a as $k => $v) {
                        $v['type'];
                        $arg = [
                            'id' => $v['type']

                        ];
                        $type[] = $category->getDataByField('category', $arg);
                        $a[$k]['type'] = $type[$k]['category'];
                    }
                    return $a;
                }
            }
        }
        $data['page'] = $page;
        $b = $products->screening($data);
//        return $b;

        foreach ($b as $k2 => $v2) {
            $arg = [
                'id' => $v2['type']
            ];

            $type2[] = $category->getDataByField('category', $arg);
            $b[$k2]['type'] = $type2[$k2]['category'];
        }
        return $b;
    }

    /**
     * 商品评价
     * @desc 商品评价添加
     * @return boolean rs true表示成功,false失败
     */
    public function review()
    {
        $domain = new Domain_ProductsReview();

        $data = [
            'uid' => $this->uid,
            'gid' => $this->gid,
            'message' => $this->message,
            'score' => $this->score,
            'time' => date('Y-m-d H:i:s')
        ];

        $rs = $domain->add($data);

        return $rs ? true : false;
    }

    /**
     * 商品评价列表
     * @desc 根据gid获取评价列表,没有返回空
     * @return string id 评价id
     * @return string message 评价信息
     * @return string score 评分
     * @return string time 评价时间
     * @return string username 用户名
     */
    public function reviewList()
    {
        $domain = new Domain_ProductsReview();

        return $domain->getList($this->gid);
    }

    /**
     * 上架商品功能
     * @desc 上架商品功能
     * @return int 0 无更新，或者数据没变化
     * @return int number 正常更新,数字多少表示,成功多少条
     * @return boolean false 无更新，或者数据没变化
     */
    public function shelves()
    {
        $products = new Domain_HomePageProducts();
        $shop = new Domain_HomePageShop();

        $new = json_decode($this->parameter, true);
        sort($new);
        $arg2 = [
            '`values`' => json_encode($new, JSON_UNESCAPED_UNICODE),
            'g_id' => $this->gid
        ];
        $id = $products->getDataByFieldSku('id', $arg2);//sku id值

        if (!$id) {
            return false;
        }

        $field = [
            'uid' => $this->uid,
            'sid' => $this->sid,
            'gid' => $this->gid,
            'nature_val' => $id,
        ];

        $number = $products->getByIdSidNatureVal('id,number', $field); //获取是否有number


        $gid = $shop->getGid($this->sid);  //查询原来是否有gid
//        $did = $shop->getDid($this->sid);

        $g = explode(',', json_decode($gid['gid'])); //上架的商品id

        $newData = [];
        //判断下架ID 是否在上架列表中
        if (!in_array($this->gid, $g)) {
            if (empty($gid['gid'])) {
                $newData = [
                    'gid' => json_encode($this->gid),
//                'shelve_id' => json_encode($rs['id'])       //如果为空,就直接插入
                ];
            } else {
                $jsonData = json_decode($gid['gid'], true);
                if (!strpos($jsonData, (string)$this->gid)) {
                    $newData = [
                        'gid' => json_encode(json_decode($gid['gid']) . ',' . $this->gid),//如果不为空,就合并数据
//                'shelve_id' => json_encode(json_decode($gid['shelve_id']) . ',' . $rs['id']),
                    ];
                }
            }
            $shop->shelves($this->sid, $newData);   //更新gid的数据
        }

        if (empty($number)) {
            $data = [
                'uid' => $this->uid,
                'sid' => $this->sid,
                'gid' => $this->gid,
                'nature_val' => $id['id'],
                'number' => $this->number ? $this->number : 0,
                'shop_price' => $this->shop_price
            ];

            $rs = $products->add($data); //获取 $rs['id'] 新增的id //不存在就添加
        } else {
            //判断是否存在, 如果存在执行更新
            $arg = [
                'id' => $number[0]['id']
            ];
            $data = [
                'number' => $number[0]['number'] + $this->number,
            ];

            $edit = $products->editNumber($arg, $data);

            return $edit ? true : false;
        }

        return $rs ? true : false;
    }

    /**
     * 上架商品内容
     * @desc 根据uid,sid,gid获取上架数据内容
     * @return int id 商品id
     * @return int type 商品类型
     * @return int image_url 图片地址
     * @return int title 商品标题
     * @return int number 上架数量
     * @return int set 所有商品
     * @return int set.nature 商品属性名
     * @return int set.details  商品详细信息
     * @return int set.details.valueID 商品属性值id
     * @return int set.details.value 商品属性值
     */
    public function shelvesData()
    {
        $product = new Domain_HomePageProducts();

        $field = 'id,type,image_url,title,retail_price';
        $data = $product->getByIdData($this->gid, $field);
        $data['price'] = $data['retail_price'];
        unset($data['retail_price']);

        if (!$data) {
            return '查询不到数据';
        }

        $arg = [
            'uid' => $this->uid,
            'sid' => $this->sid,
            'gid' => $this->gid
        ];

        $shelvesData = $product->getByIdSidNatureVal('id,number,nature_val', $arg); //上架的数据

        $number = array_column($shelvesData, 'number');

        $data['number'] = array_sum($number);//计算库商品库存两,加入数组在中

        $arg3 = [
            'g_id' => $this->gid
        ];

        $b = $product->getByIdValue($arg3);

        foreach ($b as $k => $v) {

            $nat_val = json_decode($v['values']);

            foreach ($nat_val as $v) {

                $values = $product->getByIdUidNatureVal(['id' => $v]);

                $nature[] = $values[0]['n_id'];

                $nature_val[] = $values[0];

            }
        }

        $nature = array_unique($nature);

        $nature_val = DI()->helper->unique_arr($nature_val);
        //拼接属性值和名
        foreach ($nature as $k2) {
            $natu_val = array();
            $nature_name = $product->getByNIdNature($k2);


            foreach ($nature_val as $ke) {
                if ($ke['n_id'] == $k2) {
                    $natu_val[] = array(
                        'valueID' => $ke['id'],
                        'value' => $ke['nature_val'],
                    );
                }
            }

            $date[] = array(
                'nature' => $nature_name[0]['nature'],
                'details' => $natu_val,
            );

            $data['set'] = $date;
        }
        return $data;
    }

    /**
     * 下架商品功能
     * @desc 下架商品功能
     * @return int 0 无更新，或者数据没变化
     * @return int number 正常更新,数字多少表示,成功多少条
     * @return boolean false 无更新，或者数据没变化
     * @return int code 参数错误,要下架的产品id,不再上架列表内
     */
    public function downShelves()
    {
        //根据门店id查询出来gid值

        //根据要下架的gid值,从gid字段删除  并添加到did中
        $shop = new Domain_HomePageShop();
        $products = new Domain_HomePageProducts();

        $new = json_decode($this->parameter, true);
        sort($new);
        $arg2 = [
            '`values`' => json_encode($new, JSON_UNESCAPED_UNICODE),
            'g_id' => $this->gid
        ];
        $id = $products->getDataByFieldSku('id', $arg2);//sku id值
        if (!$id) {
            return false;
        }

        $field = [
            'uid' => $this->uid,
            'sid' => $this->sid,
            'gid' => $this->gid,
            'nature_val' => $id,
        ];

        $number = $products->getByIdSidNatureVal('id,number', $field); //获取是否有number

        if (empty($number)) {
            $rs = [
                'number' => 0
            ];
        } else {
            //判断是否存在, 如果存在执行更新
            $arg = [
                'id' => $number[0]['id']
            ];
            $newNum = $number[0]['number'] - $this->number;
            $data = [
                'number' => $number ? $newNum : 0,
            ];

            $edit = $products->editNumber($arg, $data);

            return $edit ? true : false;
        }

        $gid = $shop->getGid($this->sid);  //查询原来是否有gid
        $g = explode(',', json_decode($gid['gid'])); //上架的商品id

        //判断下架ID 是否在上架列表中
        if (!in_array($this->gid, $g)) {
            $rs['code'] = -1506;
            $rs['msg'] = T("参数错误");
            return $rs;
        }

        //更新上架列表gid,
        $newGid = DI()->helper->unsetArr("$this->gid", $g); //去除已经存在的gid
        $newData = [
            'gid' => json_encode(implode(',', $newGid))
        ];

        $rs = $shop->shelves($this->sid, $newData);   //更新gid的数据

        return $rs ? true : false;
    }

    /**
     * 下架数据内容
     * @desc 根据uid,sid,gid获取下架数据内容
     * @return int id 商品id
     * @return int type 商品类型
     * @return int image_url 图片地址
     * @return int title 商品标题
     * @return int number 上架数量
     * @return int set 所有商品
     * @return int set.nature 商品属性名
     * @return int set.details  商品详细信息
     * @return int set.details.valueID 商品属性值id
     * @return int set.details.value 商品属性值
     */
    public function downShelvesData()
    {
        $product = new Domain_HomePageProducts();

        $field = 'id,type,image_url,title,retail_price';
        $data = $product->getByIdData($this->gid, $field);
        $data['price'] = $data['retail_price'];
        unset($data['retail_price']);

        $arg = [
            'uid' => $this->uid,
            'sid' => $this->sid,
            'gid' => $this->gid
        ];

        $shelvesData = $product->getByIdSidNatureVal('id,number,nature_val,shop_price', $arg); //上架的数据

        $number = array_column($shelvesData, 'number');

        $data['number'] = array_sum($number);//计算库商品库存两,加入数组在中

        $skuId = array_column($shelvesData, 'nature_val');

        foreach ($skuId as $k3 => $v3) {
            //根据nature_val 查询sku表的value值
            $field2 = '`values`';
            $arg2 = [
                'id' => $v3
            ];
            $b[] = $product->getDataByFieldSku($field2, $arg2);
        }

        foreach ($b as $k => $v) {
            $nat_val = json_decode($v['values']);
            foreach ($nat_val as $v) {
                $values = $product->getByIdUidNatureVal(['id' => $v]);
                $nature[] = $values[0]['n_id'];
                $nature_val[] = $values[0];
            }
        }

        $nature = array_unique($nature);

        $nature_val = DI()->helper->unique_arr($nature_val);

        //拼接属性值和名
        foreach ($nature as $k2) {
            $natu_val = array();
            $nature_name = $product->getByNIdNature($k2);
            foreach ($nature_val as $ke) {
                if ($ke['n_id'] == $k2) {
                    $natu_val[] = array(
                        'valueID' => $ke['id'],
                        'value' => $ke['nature_val'],
                    );
                }
            }
            $date[] = array(
                'nature' => $nature_name[0]['nature'],
                'details' => $natu_val,
            );

            $data['set'] = $date;
        }

        return $data;
    }

    /**
     * 商品库存
     * @desc 商品库存,需要属性值id
     * @return int $rs 库存值
     */
    public function number()
    {
        $products = new Domain_HomePageProducts();

        $data2 = [
            'sid' => $this->sid,
            'gid' => $this->gid
        ];

        $nature_val = $products->getByIdSidNatureVal('id,nature_val', $data2); //根据uid sid 查询属性值
        //判断能否查出数据
        if (!$nature_val) {
            $rs = [
                'number' => '0'
            ];
            return $rs;
        }

//        return $this->parameter;
//        $new = json_decode($this->parameter, true);
        sort($this->parameter);

        $arg2 = [
            '`values`' => json_encode($this->parameter, JSON_UNESCAPED_UNICODE),
            'g_id' => $this->gid
        ];

        $id = $products->getDataByFieldSku('id', $arg2);//sku id值
//        return $id;

        $field = [
            'sid' => $this->sid,
            'gid' => $this->gid,
            'nature_val' => $id['id']
        ];

        $number = $products->getByIdSidNumber('number,shop_price', $field); //根据sid uid skuId 查询数量
        if ($number) {
            $rs = [
                'number' => $number['number'],
                'shop_price' => $number['shop_price'] ? $number['shop_price'] : 0,
            ];
        } else {
            $rs = [
                'number' => '0',
                'shop_price' => '0'
            ];
        }
        return $rs;
    }

    /**
     * 查找门店对应商品的总库存
     * @desc 查找门店对应商品的总库存
     * @return int number 总库存值
     */
    public function totalNumber(){
        $products = new Domain_HomePageProducts();
        $arg = [
          'sid' => $this->sid,
          'gid' => $this->gid,
        ];
        $number =  $products->getByIdSidNatureVal('number',$arg);
        return [
            'number' => array_sum(array_column($number,'number'))
        ];
    }
}


